/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fullalbum.dao;

import fullalbum.TransactionDAO;
import fullalbum.bean.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author leoomoreira
 */
public class UserDAO {

    public User getById(Integer id) {
        String sqlUser = "select id, login, password, name from \"user\" where id = " + id + "";

        User user = new User();
        TransactionDAO dao = new TransactionDAO();

        ResultSet resultSetUser = dao.executeQuery(sqlUser);
        
        try {
            while (resultSetUser != null && resultSetUser.next()) {
                user.setId(Integer.parseInt(resultSetUser.getString("id")));
                user.setName(resultSetUser.getString("name"));
                user.setLogin(resultSetUser.getString("login"));
                user.setPassword(resultSetUser.getString("password"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        dao.commit();
        dao.close();
        return user;
    }

    public boolean changePassword(Integer id, String newPassword) {
        boolean result = false;

        String sql = "update \"user\" set password = '" + newPassword + "' where id = " + id;
        
        TransactionDAO dao = new TransactionDAO();

        int updateNumber = dao.update(sql);

        if (updateNumber > 0) {
            dao.commit();
            result = true;
        }
        else {
            dao.rollback();
        }
        dao.close();
        
        return result;
    }

}
